package com.evany.cloud.evanySolr.controller;

import com.evany.cloud.evanyCommon.util.IdUtil;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.Random;

/**
 * 测试 solr 服务
 */
@Controller
public class TestSolrController {

    @Autowired
    private SolrClient client;


    @RequestMapping("/query")
    @ResponseBody
    public Object query(String param) throws Exception {
        SolrQuery params = new SolrQuery();
        //查询条件, 这里的 q 对应 下面图片标红的地方
        params.set("q", "*");
        //过滤条件
//        params.set("fq", "product_price:[100 TO 100000]");
        //排序
        //      params.addSort("product_price", SolrQuery.ORDER.asc);

        //分页
        params.setStart(0);
        params.setRows(200);
        //默认域
//        params.set("df", "product_title");

        //只查询指定域
        // params.set("fl", "id,product_title,product_price");

        //高亮
        //打开开关
        params.setHighlight(true);
        //指定高亮域
        params.addHighlightField("product_title");
        //设置前缀
        params.setHighlightSimplePre("<span style='color:red'>");
        //设置后缀
        params.setHighlightSimplePost("</span>");
        QueryResponse queryResponse = client.query(params);
        return queryResponse.getResults();
    }

    @RequestMapping("/add")
    @ResponseBody
    public Object add() throws Exception {
        long id = IdUtil.generateId();
        SolrInputDocument doc = new SolrInputDocument();
        doc.setField("id", id);
        doc.setField("title", "test_" + new Random().nextInt(1000));
        doc.setField("content", "我是中国人, 我爱中国_" + new Random().nextInt(1000));
        doc.setField("timestamp", new Date());
        client.add(doc);
        UpdateResponse updateResponse = client.commit();
        return id;
    }

    @RequestMapping("/delById/{id}")
    @ResponseBody
    public Object delById(@PathVariable("id") String id) throws Exception {
        UpdateResponse response = client.deleteById(id);
        return response.getStatus() + "_" + response.getQTime();
    }

    @RequestMapping("/deleteAll")
    @ResponseBody
    public Object deleteAll() throws Exception {
        SolrQuery params = new SolrQuery();
        params.set("q", "*");
        UpdateResponse response = client.deleteByQuery(params.getQuery());
        client.commit();
        return response.getStatus() + "_" + response.getQTime();
    }

}
